var server = null;
server = "wss://call.ykstx.com:8189";
var janus = null;
var sipcall = null;
var jsepHandle = null;
var opaqueId = "siptest-" + Janus.randomString(12);
var spinner = null;
var selectedApproach = "secret";
var registered = false;
var incoming = null;
var reCallCount = 0;
var seatStatus = 0;
var activeHangUp = 0;
var activeHangUpCount = 0;
var callInterval = null;
var ringCount = 0;
var ringInterval = null;
var hangUpType = 1;
var callType = 1;
var hangUpCode = "";
var hangUpMsg = "";
var callBeginTime = "";
var callConnectTime = "";
var callHangUpTime = "";
function initJanus() {
	Janus.init({
		debug : "all",
		callback : function() {
			if (!Janus.isWebrtcSupported()) {
				return;
			}
			janus = new Janus(
				{
					server : server,
					success : function() {
						janus.attach(
							{
								plugin : "janus.plugin.sip",
								opaqueId : opaqueId,
								success : function(pluginHandle) {
									sipcall = pluginHandle;
									registerSip();
								},
								error : function(error) {
									Janus.error("  -- Error attaching plugin...", error);
								},
								consentDialog : function(on) {
									Janus.debug("Consent dialog should be " + (on ? "on" : "off") + " now");
								},
								mediaState : function(medium, on) {
									Janus.log("Janus " + (on ? "started" : "stopped") + " receiving our " + medium);
								},
								webrtcState : function(on) {
									Janus.log("Janus says our WebRTC PeerConnection is " + (on ? "up" : "down") + " now");
								},
								onmessage : function(msg, jsep) {
									Janus.debug(" ::: Got a message :::");
									Janus.debug(msg);
									var error = msg["error"];
									if (error != null && error != undefined) {
										if (!registered) {
										} else {
											sipcall.hangup();
										}
										return;
									}
									var result = msg["result"];
									if (result !== null && result !== undefined && result["event"] !== undefined && result["event"] !== null) {
										var event = result["event"];
										if (event === 'registration_failed') {
											Janus.warn("Registration failed: " + result["code"] + " " + result["reason"]);
											return;
										}
										if (event === 'registered') {
											Janus.log("登录成功 ！Successfully registered as " + result["username"] + "!");
											//console.log("Successfully registered as " + result["username"] + "!");
											if (!registered) {
												registered = true;
											}
											seatStatus = 2;
										} else if (event === 'calling') {
											pausePayMusic();
											Janus.log("响铃 Waiting for the peer to answer...");
											seatStatus = 6;
											callBeginTime = dateFtt(new Date(), "yyyy-MM-dd HH:mm:ss");
										} else if (event === 'incomingcall') {
											Janus.log("电话呼入 Incoming call22 from " + result["username"] + "!");
											jsepHandle = jsep;
											callType = 2;
											var myuser = "";
											myuser = result["username"].substring(4);
											myuser = myuser.substring(0, myuser.indexOf('@'));
											$("#callMobile").val(myuser);
											openCallPhone(myuser);
											if (Ext.getCmp("call_type") != null
												&& Ext.getCmp("call_type") != undefined) {
												Ext.getCmp("call_type").setValue("呼入");
											}
											seatStatus = 4;
											try {
												ringtone.play();
											} catch (e) {} // 播放来电振铃
										} else if (event === 'accepting') {
											pausePayMusic();
											Janus.log("呼叫应答 " + result["username"] + " accepting the call!");
											seatStatus = 6;
											reCallCount = 0;
											hangUpCode = "";
											hangUpMsg = "";
											hangUpType = 1; 
										} else if (event === 'progress') {
											Janus.log("呼叫进度 There's early media from " + result["username"] + ", wairing for the call!");
											Janus.log(jsep);
											if (jsep !== null && jsep !== undefined) {
												sipcall.handleRemoteJsep({
													jsep : jsep,
													error : doHangup
												});
											}
											seatStatus = 6;
										} else if (event === 'accepted') {
											pausePayMusic();
											Janus.log("呼叫接通  accepted the call!");
											//console.log(result["username"] + " accepted the call!");
											Janus.log(jsep);
											try {
												ringtone.pause();
											} catch (e) {}
											try {
												ringbacktone.pause();
											} catch (e) {}
											if (jsep !== null && jsep !== undefined) {
												sipcall.handleRemoteJsep({
													jsep : jsep,
													error : doHangup
												});
											}
											seatStatus = 5;
											reCallCount = 0;
											callConnectTime = dateFtt(new Date(), "yyyy-MM-dd HH:mm:ss");
											addCallRecord();
										} else if (event === 'hangup') {
											pausePayMusic();
											callHangUpTime = dateFtt(new Date(), "yyyy-MM-dd HH:mm:ss");
											hangUpCode = result["code"];
											hangUpMsg = result["reason"] + "[" + reCallCount + "]";
											sipcall.hangup();
											$('#dovideo').removeAttr('disabled').val('');
											seatStatus = 2;
											payHangupSound();
										}
									}
									controlCallBtn();
								},
								onlocalstream : function(stream) {
									Janus.debug(" ::: Got a local stream :::");
									Janus.debug(stream);
									$('#videos').removeClass('hide').show();
									if ($('#myvideo').length === 0)
										$('#videoleft').append('<video class="rounded centered" id="myvideo" width=320 height=240 autoplay playsinline muted="muted"/>');
									Janus.attachMediaStream($('#myvideo').get(0), stream);
									$("#myvideo").get(0).muted = "muted";
									if (sipcall.webrtcStuff.pc.iceConnectionState !== "completed" &&
										sipcall.webrtcStuff.pc.iceConnectionState !== "connected") {
										// No remote video yet
										$('#videoright').append('<video class="rounded centered" id="waitingvideo" width=320 height=240 />');
										if (spinner == null) {
											var target = document.getElementById('videoright');
											spinner = new Spinner({
												top : 100
											}).spin(target);
										} else {
											spinner.spin();
										}
									}
									var videoTracks = stream.getVideoTracks();
									if (videoTracks === null || videoTracks === undefined || videoTracks.length === 0) {
										$('#myvideo').hide();
										if ($('#videoleft .no-video-container').length === 0) {
										}
									} else {
										$('#videoleft .no-video-container').remove();
										$('#myvideo').removeClass('hide').show();
									}
								},
								onremotestream : function(stream) {
									Janus.debug(" ::: Got a remote stream :::");
									//console.log(" ::: Got a remote stream :::");
									Janus.debug(stream);
									if ($('#remotevideo').length === 0) {
										//$('#videoright').parent().find('h3').html('Send DTMF: <span id="dtmf" class="btn-group btn-group-xs"></span>');
										$('#videoright').append(
											'<video class="rounded centered hide" id="remotevideo" width=320 height=240 autoplay playsinline/>');
										for (var i = 0; i < 12; i++) {
											if (i < 10)
												$('#dtmf').append('<button class="btn btn-info dtmf">' + i + '</button>');
											else if (i == 10)
												$('#dtmf').append('<button class="btn btn-info dtmf">#</button>');
											else if (i == 11)
												$('#dtmf').append('<button class="btn btn-info dtmf">*</button>');
										}
										$('.dtmf').click(function() {
											// Send DTMF tone (inband)
											sipcall.dtmf({
												dtmf : {
													tones : $(this).text()
												}
											});
										// Notice you can also send DTMF tones using SIP INFO
										// 		sipcall.send({message: {request: "dtmf_info", digit: $(this).text()}});
										});
										// Show the peer and hide the spinner when we get a playing event
										$("#remotevideo").bind("playing", function() {
											$('#waitingvideo').remove();
											if (this.videoWidth)
												$('#remotevideo').removeClass('hide').show();
											if (spinner !== null && spinner !== undefined)
												spinner.stop();
											spinner = null;
										});
									}
									Janus.attachMediaStream($('#remotevideo').get(0), stream);
									var videoTracks = stream.getVideoTracks();
									if (videoTracks === null || videoTracks === undefined || videoTracks.length === 0) {
										// No remote video
										$('#remotevideo').hide();
										if ($('#videoright .no-video-container').length === 0) {
											/*$('#videoright').append(
												'<div class="no-video-container">' +
													'<i class="fa fa-video-camera fa-5 no-video-icon"></i>' +
													'<span class="no-video-text">No remote video available</span>' +
												'</div>');*/
										}
									} else {
										$('#videoright .no-video-container').remove();
										$('#remotevideo').removeClass('hide').show();
									}
								},
								oncleanup : function() {
									Janus.log(" ::: Got a cleanup notification :::");
									//console.log(" ::: Got a cleanup notification :::");
									$('#myvideo').remove();
									$('#waitingvideo').remove();
									$('#remotevideo').remove();
									$('.no-video-container').remove();
									$('#videos').hide();
									$('#dtmf').parent().html("Remote UA");
								}
							});
					},
					error : function(error) {
						Janus.error(error);
					//window.location.reload();
					},
					destroyed : function() {
						//window.location.reload();
					}
				});
		//yhy });
		}
	});
}
var callTimeCount = 0;
function callTimeInterval() {
	callTimeCount += 1;
	if (callTimeCount >= 3) {
		window.clearInterval(callInterval);
		activeHangUpCount = 2;
	}
}


function ringTimeInterval() {
	ringCount += 1;
	showHangupTip();
}

function cleanRingTimeInterval() {
	ringCount = 0;
	if (ringInterval != null) {
		window.clearInterval(ringInterval);
	}
	showHangupTip();
}

function showHangupTip() {
	if (ringCount > 0) {
		//$("#hangup").html("挂断(请振玲30秒后挂断)[" + ringCount + "秒]");
	} else {
		//$("#hangup").html("挂断(请振玲30秒后挂断)");
	}
}

function registerSip() {
	seatStatus = $("#seatStatus").val();
	if (seatStatus == "1") {
		var seatHost = $("#seatHost").val();
		var seatPort = $("#seatPort").val();
		var channelId = $("#channelId").val();
		var password = $("#channelPwd").val();
		var username = "sip:" + channelId + "@" + seatHost + ":" + seatPort;
		var sipserver = "sip:" + seatHost + ":" + seatPort;
		var register = {
			"request" : "register",
			"username" : username
		};
		register.authuser = channelId;
		register["secret"] = password;
		register["proxy"] = sipserver;
		register.display_name = channelId;
		register.force_udp = true;
		//console.log(register);
		sipcall.send({
			"message" : register
		});
	}
}

function reCallMobile() {
	var phone = $("#callMobile").val();
	doCall(phone);
	reCallCount += 1;
	console.log("电话重拨~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~：" + reCallCount);
}

function hangUpReCallMobile() {
	var phone = $("#callMobile").val();
	doCall(phone);
	activeHangUpCount += 1;
	console.log("挂断电话重拨~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~：" + reCallCount);
}

function doCall(phone) {
	console.log("yoooya call mobile:" + phone);
	callTimeCount = 0;
	callConnectTime = "";
	callHangUpTime = "";
	callBeginTime = "";
	var seatHost = $("#seatHost").val();
	var seatPort = $("#seatPort").val();
	var channelId = $("#channelId").val();
	var username = "sip:" + phone + "@" + seatHost + ":" + seatPort;
	doVideo = false;
	sipcall.createOffer(
		{
			media : {
				audioSend : true,
				audioRecv : true,
				videoSend : doVideo,
				videoRecv : doVideo
			},
			success : function(jsep) {
				Janus.debug("Got SDP!");
				var body = {
					request : "call",
					uri : username
				};
				sipcall.send({
					"message" : body,
					"jsep" : jsep
				});
				callType = 1;
			}/*,
			error : function(error) {
				alert("无法识别麦克风");
				Janus.error("WebRTC error...", error);
			}*/
		});
}

function doConnect() {
	var doAudio = true,
		doVideo = true;
	var offerlessInvite = false;
	if (jsepHandle !== null && jsepHandle !== undefined) {
		doAudio = (jsepHandle.sdp.indexOf("m=audio ") > -1);
		doVideo = (jsepHandle.sdp.indexOf("m=video ") > -1);
		Janus.debug("Audio " + (doAudio ? "has" : "has NOT") + " been negotiated");
		Janus.debug("Video " + (doVideo ? "has" : "has NOT") + " been negotiated");
	} else {
		Janus.log("This call doesn't contain an offer... we'll need to provide one ourselves");
		offerlessInvite = true;
		doVideo = false;
	}
	incoming = null; //yhy 自动应答
	var sipcallAction = (offerlessInvite ? sipcall.createOffer : sipcall.createAnswer);
	sipcallAction(
		{
			jsep : jsepHandle,
			media : {
				audio : doAudio,
				video : doVideo
			},
			success : function(jsep) {
				Janus.debug("Got SDP " + jsep.type + "! audio=" + doAudio + ", video=" + doVideo);
				Janus.debug(jsep);
				var body = {
					request : "accept"
				};
				sipcall.send({
					"message" : body,
					"jsep" : jsep
				});
				$('#call').removeAttr('disabled').html('Hangup')
					.removeClass("btn-success").addClass("btn-danger")
					.unbind('click').click(doHangup);
			},
			error : function(error) {
				Janus.error("WebRTC error:", error);
				alert("WebRTC error... " + JSON.stringify(error));
				// Don't keep the caller waiting any longer, but use a 480 instead of the default 486 to clarify the cause
				var body = {
					"request" : "decline",
					"code" : 480
				};
				sipcall.send({
					"message" : body
				});
			}
		});
}

function doHangup() {
    console.log("webrtc2sip.js...doHangup...1..")
	hangUpType = 2;
	if (callType == 1) {
        console.log("webrtc2sip.js...doHangup...2..")
		var hangup = {
			"request" : "hangup"
		};
		sipcall.send({
			"message" : hangup
		});
		sipcall.hangup();
        console.log("webrtc2sip.js...doHangup...3..")
	} else {
        console.log("webrtc2sip.js...doHangup...4..")
		var body = {
			"request" : "decline",
			"code" : 487
		};
		sipcall.send({
			"message" : body
		});
        console.log("webrtc2sip.js...doHangup...5..")
	}
    console.log("webrtc2sip.js...doHangup...6..")


}



function addCallLog() {
	var businessTagMobileId = $("#businessTagMobileId").val();
	var callMobile = $("#callMobile").val();
	var ucsTelno = $("#userName").val();
	var params = {
		"hangUpType" : hangUpType,
		"hangUpCode" : hangUpCode,
		"hangUpMsg" : hangUpMsg,
		"mobile" : callMobile,
		"callBeginTimeStr" : callBeginTime,
		"callConnectTimeStr" : callConnectTime,
		"callHangUpTimeStr" : callHangUpTime,
		"ucsTelno" : ucsTelno,
		"mobileId" : businessTagMobileId
	};
	var url = ctx + "/wx/purview//tag/call/log";
	$.post(url, params, function(data) {}, 'json');
}


function dateFtt(date, fmt) { //author: meizz 
	var o = {
		"M+" : date.getMonth() + 1, //月份 
		"d+" : date.getDate(), //日 
		"H+" : date.getHours(), //小时 
		"m+" : date.getMinutes(), //分 
		"s+" : date.getSeconds(), //秒 
		"q+" : Math.floor((date.getMonth() + 3) / 3), //季度 
		"S" : date.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}